import {createRouter, createWebHistory, RouteRecordRaw} from "vue-router";
import {AuthStore} from "@/store/AuthStore";
import {Message} from "@/utils/Message";

const routes: Array<RouteRecordRaw> = [
    {
        path: "/",
        redirect: {
            name: "list"
        }
    },
    {
        path: "",
        name: "index",
        component: () => import("@/views/article/Index.vue"),
        children: [
            {
                name: "list",
                path: "",
                component: () => import("@/components/article/articleContentBar.vue")
            },
            {
                name: "article",
                path: "article/:id",
                component: () => import("@/views/article/ArticleView.vue")
            },
            {
                name: "user",
                path: "user/:id",
                component: () => import("@/views/user/UserHomePage.vue")
            },
            {
                name: "share",
                path: "share",
                component: () => import("@/views/share/SharePage.vue")
            },
            {
                name: "milestone",
                path: "milestone",
                component: () => import("@/views/milestone/MileStone.vue")
            },
        ]
    },
    {
        name: "editor",
        path: "/editor",
        component: () => import("@/views/article/EditorPage.vue")
    },
    {
        path: "/login",
        name: "login",
        component: () => import("@/views/auth/LoginPage.vue")
    },
    {
        path: "/register",
        name: "register",
        component: () => import("@/views/auth/RegisterPage.vue")
    },
    {
        path: "/changePassword",
        name: "changePassword",
        component: () => import("@/views/auth/ChangePasswordPage.vue")
    },
];

const AppRouter = createRouter({
    history: createWebHistory(process.env.BASE_URL),
    routes
});

/**
 * 路由前置守卫
 */
AppRouter.beforeResolve(async (to, from) => {
    // 获取认证状态
    const authStore = AuthStore();

    // 如果前往的页面需要认证，则校验登录状态
    if (to.meta?.auth) {
        if (!authStore.isLogin()) {
            Message.error("用户未登陆");
            return {name: "login"};
        }
    }

    //  如果已经登录后，再前往认证页面则重定向回主页面
    if (authStore.isLogin() && (to.name == "login" || to.name == "register" || to.name == "changePassword")) {
        return {name: "index"};
    }
});
export default AppRouter;
